package com.example.test.advice.第五章_数组和集合.建议78_减少HashMap中元素的数量;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Client {

    @Test
    public void testHashMap(){//内存溢出
        Map<String,String> map = new HashMap<>();
        final Runtime rt = Runtime.getRuntime();
        //JVM中止前记录内存信息
        rt.addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuffer sb = new StringBuffer();
                long heapMaxSize = rt.maxMemory() >>20;
                sb.append("最大可用内存："+heapMaxSize+"M\n");
                long total = rt.totalMemory() >>20;
                sb.append("堆内存大小："+total+"M\n");
                long free = rt.freeMemory()>>20;
                System.out.println("空闲内存大小："+free+"M");
                System.out.println(sb);
            }
        }));

        //放入40万个键值对
        for(int i = 0;i<393217;i++){
            map.put("key"+i,"value"+i);
        }
    }

    @Test
    public  void testArrayList() {//内存没有溢出
        List<String> list = new ArrayList<>();
        final Runtime rt = Runtime.getRuntime();
        //JVM中止前记录内存信息
        rt.addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                StringBuffer sb = new StringBuffer();
                long heapMaxSize = rt.maxMemory() >>20;
                sb.append("最大可用内存："+heapMaxSize+"M\n");
                long total = rt.totalMemory() >>20;
                sb.append("堆内存大小："+total+"M\n");
                long free = rt.freeMemory()>>20;
                System.out.println("空闲内存大小："+free+"M");
                System.out.println(sb);
            }
        }));

        //放入40万个键值对
        for(int i = 0;i<393217;i++){
            list.add("value"+i);
        }
    }
}
